<html>
    <head>
        <style type="text/css">
        video {
            display: none;
        }
        </style>
    </head>
<body>
<video id="video">
    <source src="resources/canvas_video.webm" type="video/webm" />
</video>
<canvas id="videoPattern" width="100" height="100"></canvas>
<canvas id="imagePattern" width="100" height="100"></canvas>
<canvas id="canvasPattern" width="100" height="100"></canvas>
<script>
function drawPatternFromImageSourceToCanvas(offscreenCanvas, imageSource, outputCanvas, repetitionType) {
    var offscreenCanvasCtx = offscreenCanvas.getContext('2d');
    var pattern = offscreenCanvasCtx.createPattern(imageSource, repetitionType);
    offscreenCanvasCtx.fillStyle = pattern;
    offscreenCanvasCtx.fillRect(0, 0, offscreenCanvas.width, offscreenCanvas.height);
    var outputCanvasRenderer = outputCanvas.getContext("bitmaprenderer");
    outputCanvasRenderer.transferFromImageBitmap(offscreenCanvas.transferToImageBitmap());
}

function createPatternFromVideo() {
    var canvas_video = new OffscreenCanvas(100, 100);
    var video = document.getElementById('video');
    var videoOnPlay = function() {
        video.removeEventListener("playing", videoOnPlay);
        drawPatternFromImageSourceToCanvas(canvas_video, video, document.getElementById('videoPattern'), "no-repeat");
    }; 
    video.addEventListener("playing", videoOnPlay, true);
    video.play();
}

function createPatternFromImage() {
    var canvas_image = new OffscreenCanvas(100, 100);
    var image = new Image(); 
    var imageOnLoad = function() {
        image.removeEventListener("load", imageOnLoad);
        drawPatternFromImageSourceToCanvas(canvas_image, image, document.getElementById('imagePattern'), "repeat");
    };
    image.addEventListener("load", imageOnLoad);
    image.src = "resources/pattern.png";
}

function createPatternFromCanvas() {
    var canvas_canvas = new OffscreenCanvas(100, 100);
    var htmlCanvas = document.createElement('canvas');
    htmlCanvas.width = 10;
    htmlCanvas.height = 50;
    var htmlCanvasCtx = htmlCanvas.getContext("2d");
    htmlCanvasCtx.fillStyle = "blue";
    htmlCanvasCtx.fillRect(0, 0, 5, 50);
    htmlCanvasCtx.fillStyle = "red";
    htmlCanvasCtx.fillRect(5, 0, 10, 50);
    drawPatternFromImageSourceToCanvas(canvas_canvas, htmlCanvas, document.getElementById('canvasPattern'), "repeat-x");

}

createPatternFromVideo();
createPatternFromImage();
createPatternFromCanvas();
</script>
</body>
</html>
